import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getHomeCategory } from '@/apis/category.js'

export const useCategoryStore = defineStore('category', () => {
  const homeCategoryList = ref([])
  let pending = null

  const queryHomeCategoryList = async () => {
    if (homeCategoryList.value.length) return Promise.resolve(homeCategoryList.value)
    if (pending) return pending // 关键：同一次请求

    pending = getHomeCategory()
      .then((res) => {
        homeCategoryList.value = Array.isArray(res) ? res : []
        return homeCategoryList.value
      })
      .finally(() => {
        pending = null
      })

    return pending
  }

  return {
    queryHomeCategoryList,
    homeCategoryList,
  }
})
